<template>
  <a-drawer
    :width="720"
    title="新增部门"
    @close="show=false"
    :visible="show"

  >
    <a-form :form="form">
      <a-form-item label="父级部门" v-bind="formItemLayout">
        <span>{{createRootDept?'无':parentDept.name}}</span>
      </a-form-item>
      <a-form-item label="部门名称" v-bind="formItemLayout">
        <a-input v-decorator="field('name','部门名称')"/>
      </a-form-item>
    </a-form>
    <div :style="drawerBottom">
      <a-button :style="{marginRight: '8px'}" @click="show=false">
        取消
      </a-button>
      <a-button @click="submitForm" type="primary">确定</a-button>
    </div>
  </a-drawer>
</template>

<script>

  import {drawerBody, drawerBottom, field} from '@/utils/util'
  import {createDept} from '@/api/dept'

  export default {

    name: 'CreateDeptDialog',

    data() {
      return {
        drawerBody,
        drawerBottom,
        formItemLayout: {
          labelCol: {span: 5},
          wrapperCol: {span: 19}
        },
        form: this.$form.createForm(this),
        show: false,
        parentDept: {}
      }
    },

    props: {
      createRootDept: {
        type: Boolean,
        default: false,
        required: false
      }
    },

    created() {

    },

    methods: {

      field,

      submitForm() {
        this.doCreateDept()
      },

      doCreateDept() {
        this.form.validateFields((errors, values) => {
          let newRow = Object.assign({}, values)
          if(this.createRootDept){
            newRow.parent = 0
            newRow.parents = '0,'
            newRow.children = []
          }else{
            newRow.parent = this.parentDept.id
            newRow.parents = `${this.parentDept.parents}${this.parentDept.id},`
            newRow.children = []
          }
          if (!errors) {
            createDept(newRow, this.createRootDept).then(resp => {
              this.show = false
              newRow.id = resp.result.id
              this.$emit('success', newRow)
            })
          }
        })
      },

      open(parentDept) {
        console.log('----=== %o', parentDept)
        this.parentDept = parentDept
        this.show = true
        this.form.resetFields()
      },

      close() {
        this.show = false
      }

    }

  }
</script>
